{"componentChunkName":"component---src-templates-post-jsx","path":"/[스프링입문]2/","result":{"data":{"site":{"siteMetadata":{"title":"SUbbb"}},"markdownRemark":{"id":"7c6e6830-1b5c-58ac-9281-1dadf3465ae2","excerpt":"스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술을 들으며 정리하는 POST입니다. 전체적인 흐름 Spring Project 생성 Spring boot로 웹 서버 실행 회원 도메인 개발 웹 MVC 개발 DB 연동 - JDBC, JPA, Spring data JPA 테스트 케이스 작성 🔍 정적 컨텐츠 ⛏ 정적 컨텐츠란? 서버에 저장되…","html":"<p><em><strong><a href=\"https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8\">스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술</a>을 들으며 정리하는 POST입니다.</strong></em></p>\n<blockquote>\n<p><strong>전체적인 흐름</strong></p>\n<ul>\n<li>Spring Project 생성</li>\n<li>Spring boot로 웹 서버 실행</li>\n<li>회원 도메인 개발</li>\n<li>웹 MVC 개발</li>\n<li>DB 연동 - JDBC, JPA, Spring data JPA</li>\n<li>테스트 케이스 작성</li>\n</ul>\n</blockquote>\n<h2>🔍 정적 컨텐츠</h2>\n<h3>⛏ 정적 컨텐츠란?</h3>\n<ul>\n<li>서버에 저장되어 있고 <strong>변화 없이</strong> 브라우저로 뿌려지는 컨텐츠(파일)</li>\n<li>요청에 따라 응답만을 수행</li>\n</ul>\n<p><strong>Spring Boot는 정적 컨텐츠 기능 자동 제공</strong><br/>\n→ <a href=\"https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content\">https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content</a></p>\n<ul>\n<li><code class=\"language-text\">/static</code> 폴더에서 정적 컨텐츠를 찾아서 제공한다.</li>\n</ul>\n<p><strong><code class=\"language-text\">/static</code> 에 <code class=\"language-text\">hello-static.html</code> 을 생성 및 작성해보자.</strong></p>\n<p><img src='https://images.velog.io/images/bsu1209/post/730e0fbd-5aee-4bbc-aeff-2726a8d49a37/image.png' width='25%'><img src='https://images.velog.io/images/bsu1209/post/60f18df8-7d2f-4280-b638-f4d4dd7520f5/image.png' width='50%'></p>\n<ul>\n<li>파일 작성 후 서버를 동작시키면, <strong><a href=\"http://localhost:8080/hello-static.html\">http://localhost:8080/hello-static.html</a></strong> 에서 작성한 정적 컨텐츠인 <code class=\"language-text\">html</code> 파일을 확인할 수 있다.\n<img src='https://images.velog.io/images/bsu1209/post/3634c932-506e-4040-9f55-33baab3968bb/%E1%84%86%E1%85%AE%E1%84%8C%E1%85%A6.drawio.png' width='80%'></li>\n</ul>\n<hr>\n<h2>🔍 MVC와 템플릿 엔진</h2>\n<h3>⛏ 템플릿 엔진이란?</h3>\n<ul>\n<li>서버에서 <strong>동적으로</strong> 파일을 바꿔서 브라우저로 뿌려주는 엔진</li>\n<li>jsp, php 등이 있다.</li>\n<li>이를 위해 필요한 <strong>Model, View, Controller</strong>를 합쳐 <strong>MVC</strong>라고 한다.</li>\n<li>\n<p>예전에는 View만으로 개발을 진행했다면, 이제는 <strong>View는 화면을 그리는 데에만 집중</strong>하고, <strong>Model &#x26; Controller는 Business logic과 관련있거나, 내부적인 것들을 처리하는데 집중</strong>하기 위해 이를 분리하였다.</p>\n<ul>\n<li>\n<p><strong>!면접 질문!</strong></p>\n<ul>\n<li>유지보수성</li>\n<li>애플리케이션의 확장성</li>\n<li>유연성 증가(클라이언트의 새로운 요구사항에 대해 최소한의 비용으로 보다 유연하게 대처)</li>\n<li>중복코딩의 문제점 감소</li>\n</ul>\n</li>\n<li>그렇지 않으면 유지, 보수에 엄청난 시간이 필요할 것이다 ...</li>\n</ul>\n</li>\n</ul>\n<blockquote>\n<p><strong>정적 컨텐츠와 다른 점</strong>\n서버에서 뿌려질 컨텐츠에 동적으로 변화를 줄 수 있다.</p>\n</blockquote>\n<p>이번에는 <strong>MVC를 이용하여 Parameter를 받는 Controller</strong>를 생성해보자.</p>\n<p><strong><code class=\"language-text\">controller/HelloController.java</code></strong><br/></p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@GetMapping(&quot;hello-mvc&quot;)\npublic String helloMvc(@RequestParam (&quot;name&quot;) String name, Model model) {\n    model.addAttribute(&quot;name&quot;, name);\n    return &quot;hello-template&quot;;\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">@RequestParam</code> annotation은 HTTP request parameter를 method의 parameter로 전달받을 때 사용한다. <code class=\"language-text\">form</code> 에서의 <code class=\"language-text\">input</code> 의 <code class=\"language-text\">name</code> 과 매칭되어 해당 값을 받아올 수 있다.</li>\n<li><code class=\"language-text\">String name</code> 에 해당 값을 담고, <code class=\"language-text\">Model model</code> 을 이용하여 <code class=\"language-text\">View</code> 에서 rendering 시 사용</li>\n<li><code class=\"language-text\">model.addAttribute</code> method로 <strong><code class=\"language-text\">key</code></strong> 가 <strong>\"name\"</strong> 이고, <strong><code class=\"language-text\">변수이름</code></strong> 이 <strong><code class=\"language-text\">name</code></strong> 인 값을 가져와서 <code class=\"language-text\">View</code> 로 전달한다.</li>\n</ul>\n<p><strong><code class=\"language-text\">resources/templates/hello-templates.html</code></strong><br/></p>\n<deckgo-highlight-code language=\"html\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">&lt;!DOCTYPE html&gt;\n&lt;html lang=&quot;en&quot; xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;\n&lt;body&gt;\n    &lt;p th:text=&quot;&#39;hello&#39; + ${name}&quot;&gt;hello! empty&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;</code>\n        </deckgo-highlight-code>\n<ul>\n<li>\n<p><code class=\"language-text\">xmlns:th=\"~\"</code> 로 <code class=\"language-text\">thymeleaf</code> 템플릿을 사용함을 명시</p>\n<ul>\n<li>thymeleaf의 장점은, 위와 같이 저장한 파일 자체를 서버없이 열어도 해당 파일의 소스코드를 그대로 확인 가능하다.</li>\n<li>서버가 동작하게 되면, <code class=\"language-text\">th:text</code> 에 있는 값으로 <code class=\"language-text\">hello! empty</code> 가 치환된다.</li>\n</ul>\n</li>\n</ul>\n<p>서버를 동작시켜 <a href=\"http://localhost:8080/hello-mvc\">http://localhost:8080/hello-mvc</a> 로 접속\n<img src='https://images.velog.io/images/bsu1209/post/eb52fa9d-b790-481a-9d82-66e07f3766c3/image.png' width='80%'></p>\n<deckgo-highlight-code language=\"bash\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">WARN 51004 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter &#39;name&#39; for method parameter type String is not present]</code>\n        </deckgo-highlight-code>\n<ul>\n<li>위와 같은 log와 함께 Error page가 나오는 것을 확인할 수 있다. 쉽게 말해 <code class=\"language-text\">name</code> parameter에 아무것도 넘겨주지 않아서 뜨는 에러라고 할 수 있다.</li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@GetMapping(&quot;hello-mvc&quot;)\npublic String helloMvc(@RequestParam (name = &quot;name&quot;) String name, Model model) {\n    model.addAttribute(&quot;name&quot;, name);\n    return &quot;hello-template&quot;;\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li>위와 같이, parameter의 이름을 명시하고, <code class=\"language-text\">required</code> option은 기본값이 <code class=\"language-text\">true</code> 이므로 그대로 둔다.</li>\n</ul>\n<p>이제 <a href=\"http://localhost:8080/hello-mvc?name=spring\">http://localhost:8080/hello-mvc?name=spring</a> 으로 접속해보자.\n<img src='https://images.velog.io/images/bsu1209/post/c32434b5-6b7a-4244-99b8-672dcb8f382c/image.png' width='80%'></p>\n<ul>\n<li>\n<p>동작방식은, </p>\n<ol>\n<li>url에서 받아온 name에 대한 \"spring\" 이라는 값이 <code class=\"language-text\">public Stirng helloMvc</code> 의 <code class=\"language-text\">String name</code> 에 담기고,</li>\n<li><code class=\"language-text\">model.addAttribute</code> 를 통해 <code class=\"language-text\">name</code> 이 <code class=\"language-text\">model</code> 에 담겨, <code class=\"language-text\">hello-template</code> 으로 return</li>\n<li><code class=\"language-text\">${name}</code> 으로, <code class=\"language-text\">model</code> 에서 key값이 <code class=\"language-text\">name</code> 인 값을 가져와서 치환!</li>\n</ol>\n</li>\n</ul>\n<img src='https://images.velog.io/images/bsu1209/post/218ce6be-9030-4514-82fb-b13bd9f5cb1b/springboot.drawio.png' width='80%'>\n<hr>\n<h2>🔍 API</h2>\n<ul>\n<li><code class=\"language-text\">JSON</code> 이라는 데이터 포맷으로 서버에서 클라이언트로 <strong>데이터를 전송하는 방식</strong></li>\n</ul>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@GetMapping(&quot;hello-string&quot;)\n@ResponseBody\npublic String helloString(@RequestParam(&quot;name&quot;) String name) {\n    return &quot;hello&quot; + name;\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><code class=\"language-text\">@ResponseBody</code> 는, http에서의 body에 해당 내용을 직접 넣겠다는 의미!</li>\n<li>\n<p><strong>Template engine과 다른 점</strong>은 \"view\" 개념 없이 data가 그대로 보여진다.</p>\n<ul>\n<li>확인하기 위해, <a href=\"http://localhost:8080/hello-string?name=spring\">http://localhost:8080/hello-string?name=spring</a> 으로 접속하면, 아래와 같은 화면이 보이고, <code class=\"language-text\">페이지 소스 보기</code> 하면, html code 없이 Data만 존재하는 것을 확인할 수 있다.</li>\n</ul>\n<p><img src='https://images.velog.io/images/bsu1209/post/b865d7e2-4a4e-4894-8629-0b1dfedd010c/image.png' width='40%' style='float: left;'><img src='https://images.velog.io/images/bsu1209/post/f52aee18-4120-4abf-a60f-be8423a6a835/image.png' width='40%'></p>\n</li>\n</ul>\n<p>다음 예제는 <code class=\"language-text\">Hello</code> 객체와 <code class=\"language-text\">getName</code> &#x26; <code class=\"language-text\">setName</code>, 그리고 객체를 <code class=\"language-text\">return</code> 하는 Api 방식이다.</p>\n<deckgo-highlight-code language=\"java\" terminal=\"carbon\" theme=\"a11y-dark\" line-numbers=\"true\"  >\n          <code slot=\"code\">@GetMapping(&quot;hello-api&quot;)\n@ResponseBody\npublic Hello helloApi(@RequestParam(&quot;name&quot;) String name) {\n    Hello hello = new Hello();\n    hello.setName(name);\n    return hello;\n}\n\nstatic class Hello {\n    private String name;\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n}</code>\n        </deckgo-highlight-code>\n<ul>\n<li><a href=\"http://localhost:8080/hello-api?name=spring\">http://localhost:8080/hello-api?name=spring</a> 으로 접속하면 아래 사진에서 보이는 바와 같이 <strong><code class=\"language-text\">Key</code> &#x26; <code class=\"language-text\">Value</code></strong> 로 이루어진 <strong>JSON</strong> 구조를 확인할 수 있다.</li>\n</ul>\n<img src='https://images.velog.io/images/bsu1209/post/d466fad7-fe76-47f4-9394-f520b4a787e9/image.png' width='40%'>\n<blockquote>\n<p>mac 기준 <code class=\"language-text\">⌘ + n</code> 으로 Getter와 Setter를 생성할 수 있다.\n<code class=\"language-text\">Hello</code> Class 안에 있는 <code class=\"language-text\">String name</code> 은 <code class=\"language-text\">private</code> 이므로, 해당 변수에 대한 접근은 오직 <code class=\"language-text\">public</code> 한 <code class=\"language-text\">getName</code> or <code class=\"language-text\">setName</code> 으로만 가능하게 한다.\n→ <strong>JavaBeans</strong> 표준 방식</p>\n</blockquote>\n<img src='https://images.velog.io/images/bsu1209/post/bd1edf66-e5fb-4123-895d-2ef97cdfa424/springboot.drawio%20(1).png' width='80%'>\n<ul>\n<li>이와 같이 <code class=\"language-text\">@ResponseBody</code> 를 사용한 동작방식은,</li>\n<li>localhost:8080/hello-api로 이동하여 controller가 이를 확인</li>\n<li>template engine의 경우, 해당하는 view를 보여주기 위해 viewResolver에게 전달했지만 <code class=\"language-text\">@ResponseBody</code> 를 발견하면 <code class=\"language-text\">http</code> 응답에 해당 Data를 그대로 전달하기 위한 처리를 수행</li>\n<li>\n<p>이때, 전달하려는 Data가 문자열이 아닌 <strong>객체</strong>이므로 이에 대한 처리가 필요하다.</p>\n<ul>\n<li>Spring의 기본 정책은 객체가 오는 경우, 이를 JSON 방식으로 Http 응답에 반환하는 것</li>\n</ul>\n</li>\n<li>\n<p><code class=\"language-text\">ViewResolver</code> 대신 <code class=\"language-text\">HttpMessageConverter</code> 가 동작하여 <strong>String인 경우는 <code class=\"language-text\">StringConverter</code></strong>, <strong>객체인 경우는 <code class=\"language-text\">JsonConverter</code></strong> 를 동작시킴</p>\n<ul>\n<li>대표적인 JsonConverter library로는 <code class=\"language-text\">MappingJacksonHttpMessageConveter</code> 와 <code class=\"language-text\">GsonHttpMessageConveter</code> 가 있다.</li>\n<li>HttpMessageConverter는 클라이언트가 원하는 response 형태를 header에 명시한 경우, 이에 맞춰 선택된다. 그렇지 않은 경우는 spring이 알아서 선택!</li>\n<li>MessageConverter에 대한 자세한 정보는 참고에 있는 <strong>HttpMessageConverter</strong> 를 확인</li>\n</ul>\n</li>\n<li>Converter를 이용해 변환된 결과를 요청측으로 전달</li>\n</ul>\n<blockquote>\n<p>예전에는 JSON이 아닌 XML 방식을 사용했었는데, (ex. html code) 이는 열고 닫는 이중의 code가 필요하고, 무겁다는 단점때문에 최근에는 Simple한 JSON 형태를 많이 사용한다.</p>\n</blockquote>\n<hr>\n<h2>📌 중요한 개념</h2>\n<p>Template engine, API, Annotation, HttpMessageConverter, JavaBeans</p>\n<h2>📕 참고</h2>\n<ul>\n<li><a href=\"https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8\">스프링 입문-코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술</a></li>\n<li><a href=\"https://devbox.tistory.com/entry/Spring-%EC%BB%A8%ED%8A%B8%EB%A1%A4%EB%9F%AC-%EB%A9%94%EC%84%9C%EB%93%9C%EC%9D%98-%ED%8C%8C%EB%9D%BC%EB%AF%B8%ED%84%B0-%ED%83%80%EC%9E%85\">장인개발자를 꿈꾸는 :: 기록하는 공간</a></li>\n<li><a href=\"https://jaimemin.tistory.com/1823\">HttpMessageConverter</a></li>\n</ul>","frontmatter":{"title":"📺 2. 스프링 웹 개발 기초","date":"January 03, 2022","update":"January 03, 2022","tags":["Java","SpringBoot"],"series":"📺 스프링 입문"},"fields":{"slug":"/[스프링입문]2/","readingTime":{"minutes":8.35}}},"seriesList":{"edges":[{"node":{"id":"dff670de-9a25-5abe-9b4f-84af280c0807","fields":{"slug":"/[스프링입문]1/"},"frontmatter":{"title":"📺 1. 프로젝트 환경설정"}}},{"node":{"id":"7c6e6830-1b5c-58ac-9281-1dadf3465ae2","fields":{"slug":"/[스프링입문]2/"},"frontmatter":{"title":"📺 2. 스프링 웹 개발 기초"}}},{"node":{"id":"ffd03b02-aec7-5fe4-9a24-270be1ffa4ce","fields":{"slug":"/[스프링입문]3/"},"frontmatter":{"title":"📺 3. 회원 관리 예제"}}},{"node":{"id":"104a5bbb-2e2c-5770-80ed-c438c39a3e57","fields":{"slug":"/[스프링입문]4/"},"frontmatter":{"title":"📺 4. 스프링 빈과 의존관계"}}},{"node":{"id":"5c16c94d-5e6b-541f-b861-1bbeb45da9f8","fields":{"slug":"/[스프링입문]5/"},"frontmatter":{"title":"📺 5. 웹 MVC 개발"}}},{"node":{"id":"8b5e56c2-f7dd-5d13-92c4-4e18d9df605b","fields":{"slug":"/[스프링입문]6/"},"frontmatter":{"title":"📺 6. 스프링 DB 접근 기술"}}},{"node":{"id":"7012c442-42b4-5c43-8945-85bdce9799cd","fields":{"slug":"/[스프링입문]7/"},"frontmatter":{"title":"📺 7. AOP"}}}]},"previous":{"fields":{"slug":"/[스프링입문]1/"},"frontmatter":{"title":"📺 1. 프로젝트 환경설정"}},"next":{"fields":{"slug":"/[스프링입문]3/"},"frontmatter":{"title":"📺 3. 회원 관리 예제"}}},"pageContext":{"id":"7c6e6830-1b5c-58ac-9281-1dadf3465ae2","series":"📺 스프링 입문","previousPostId":"dff670de-9a25-5abe-9b4f-84af280c0807","nextPostId":"ffd03b02-aec7-5fe4-9a24-270be1ffa4ce"}},"staticQueryHashes":[]}